package com.liang.spring5;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Arrays;

/**
 * Created with Intellij IDEA
 *
 * @Auther: liangjy
 * @Date: 2022/01/17/11:34
 * @Description: 实现接口的动态代理
 */
public class JDKProxy {
    public static void main(String[] args) {
        //创建接口实现类的代理对象
        Class[] interfaces = {UserDao.class};
        UserDaoImpl userDao = new UserDaoImpl();
//        Proxy.newProxyInstance(JDKProxy.class.getClassLoader(), interfaces, new InvocationHandler() {
//            @Override
//            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
//                return null;
//            }
//        });//匿名内部类
        UserDao dao = (UserDao) Proxy.newProxyInstance(JDKProxy.class.getClassLoader(), interfaces, new UserDaoProxy(userDao));
        int result = dao.add(1, 2);
        System.out.println("result:".concat(String.valueOf(result)));

        System.out.println(JDKProxy.class.getClassLoader().toString());
    }
}

//创建代理对象代码
class UserDaoProxy implements InvocationHandler {
    private Object obj;

    //1、把创建的是谁的代理对象，把谁传递过来 此例应该把 UserDaoImpl 传递过来
    //有参数构造传递
    public UserDaoProxy(Object obj) {
        this.obj = obj;
    }

    //写增强的逻辑
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        //方法之前
        System.out.println(">>>>>>>方法前" + method.getName() + ": 传递的参数" + Arrays.toString(args));
        //被增强的方法执行
        Object res = method.invoke(obj, args);

        //方法之后
        System.out.println(">>>>>>>>方法后" + obj);
        return res;


    }

    /**
     * 测试结果
     * >>>>>>>方法前add: 传递的参数[1, 2]
     * add方法执行了。。。。。
     * >>>>>>>>方法后com.liang.spring5.UserDaoImpl@6e0be858
     * result:3
     * sun.misc.Launcher$AppClassLoader@18b4aac2
     *
     * Process finished with exit code 0
     */
}